/**
 * 
 */
package com.maywide.jdp.system.bean;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.maywide.jdp.core.exception.AppException;
import com.maywide.jdp.core.vo.Context;
import com.maywide.jdp.core.vo.Page;
import com.maywide.jdp.dao.Dao;
import com.maywide.jdp.dao.PageQueryTemplate;
import com.maywide.jdp.system.entities.Menu;
import com.maywide.jdp.system.vo.MenuCheckedTree;
import com.maywide.jdp.system.vo.MenuTree;

/**
 * 菜单Bean
 * 
 * @author luoyang
 * @version 1.0
 * @since JDK1.6
 */
@Component("menuBean")
@Transactional(propagation = Propagation.REQUIRED)
public class MenuBeanImpl implements MenuBean {
	/**
	 * 基础DAO
	 */
	private Dao dao = null;

	/**
	 * @param dao
	 *            the dao to set
	 */
	@Autowired
	public void setDao(Dao dao) {
		this.dao = dao;
	}

	@Override
	public void insert(Object obj) throws Exception {
		dao.insert(obj);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void remove(Class clazz,Serializable id) throws Exception {
		Object obj = dao.find(clazz, id);
		dao.remove(obj);
	}

	@Override
	public void update(Object obj) throws Exception {
		dao.update(obj);
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public Object load(Serializable id) throws Exception {
		Menu directory = dao.find(Menu.class, id);
		return directory;
	}

	@Override
	public void lock(String id) throws Exception {
		String jql = "update Menu as o set o.active = false where o.id = :id";
		Query query = dao.createQuery(jql);
		query.setParameter("id", id);
		query.executeUpdate();
	}

	@Override
	public void lockAll(String[] ids) throws Exception {
		String hql = "update Menu as o set o.active = false where o.id in (:ids)";
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("ids", ids);
		dao.executeUpdate(hql, conditions);
	}

	@Override
	public void unlock(String id) throws Exception {
		String jql = "update Menu as o set o.active = true where o.id = :id";
		Query query = dao.createQuery(jql);
		query.setParameter("id", id);
		query.executeUpdate();
	}

	@Override
	public void unlockAll(String[] ids) throws Exception {
		String hql = "update Menu as o set o.active = true where o.id in (:ids)";
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("ids", ids);
		dao.executeUpdate(hql, conditions);
	}

	@Override
	public void move(String id, String parentID) throws Exception {
		String jql = "update Menu as o set o.parent.id = :parentID where o.id = :id";
		Query query = dao.createQuery(jql);
		int row = 0;
		query.setParameter("id", id);
		query.setParameter("parentID", parentID);
		row = query.executeUpdate();
		if (row <= 0)
			throw new AppException("未发生移动操作!");
	}

	@Override
	public void move(List<String> ids, String parentID) throws Exception {
		int row = 0;
		String hql = "update Menu as o set o.parent.id = :parentID where o.id in (:ids)";
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("ids", ids);
		conditions.put("parentID", parentID);
		row = dao.executeUpdate(hql, conditions);
		if (row <= 0)
			throw new AppException("未发生移动操作!");
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<MenuTree> tree(Map<String, Object> parameters) throws Exception {
		StringBuffer buf = new StringBuffer()
				.append("select distinct o.ID as id,")
				.append("o.MNU_CODE as code,")
				.append("o.MNU_NAME as name,")
				.append("o.MNU_TEXT as text,")
				.append("o.MNU_TAB_INDEX as tabIndex,")
				.append("o.MNU_WIDTH as width,")
				.append("o.MNU_HEIGHT as height,")
				.append("o.MNU_ICON as menuIcon,")
				.append("o.MNU_ICON_CLS as menuIconCls,")
				.append("o.MNU_URL as url,")
				.append("o.MNU_PARENT_ID as parentID,")
				.append("o.MNU_DESC as description,")
				.append("o.MNU_ACTIVE as active,")
				.append("decode(sign(count(sub.ID)),1,0,1) as leaf")
				.append(" from SYS_MENU o")
				.append(" left join")
				.append(" SYS_MENU sub on o.ID = sub.MNU_PARENT_ID")
				.append(" INNER JOIN SYS_MENU_ROLE_REL rel")
				.append(" ON o.ID         = rel.MENU_ID")
				.append(" INNER JOIN SYS_ROLE r")
				.append(" ON r.ID         = rel.ROLE_ID ");
				if(parameters.containsKey("roleIDs")) {
					String[] roleIDs = (String[]) parameters.get("roleIDs");
					if(roleIDs != null && roleIDs.length > 0) {
						buf.append(" AND r.ID IN (:roleIDs)");
					}
				}
				buf.append(" WHERE");
				if (parameters.containsKey("parentID"))
					buf.append(" o.ID IN(SELECT org.ID FROM SYS_MENU org WHERE org.MNU_PARENT_ID = :parentID AND org.MNU_ACTIVE = 1)");
				else if(parameters.containsKey("rootID"))
					buf.append(" o.ID = :rootID");
				else
					buf.append(" o.ID IN(SELECT org.ID FROM SYS_MENU org WHERE org.MNU_PARENT_ID IS NULL AND org.MNU_ACTIVE = 1)");
				buf.append(" AND");
				buf.append(" o.MNU_ACTIVE = 1 AND o.REMOVED = 0");
				buf.append(
						" group by o.ID,o.MNU_CODE,o.MNU_NAME,o.MNU_TEXT,o.MNU_TAB_INDEX,o.MNU_WIDTH,o.MNU_HEIGHT,o.MNU_ICON,o.MNU_ICON_CLS,o.MNU_URL,o.MNU_PARENT_ID,o.MNU_DESC,o.MNU_ACTIVE");

		String sql = buf.toString();
		return dao
		.executeNativeQuery(sql, parameters, MenuTree.class,
				"com.maywide.jdp.system.entities.Menu.menuTree");
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<MenuCheckedTree> treeGrid(Map<String, Object> parameters) throws Exception {
		StringBuffer buf = new StringBuffer()
		.append("select distinct o.ID as id,")
		.append("o.MNU_CODE as code,")
		.append("o.MNU_NAME as name,")
		.append("o.MNU_TEXT as text,")
		.append("o.MNU_TAB_INDEX as tabIndex,")
		.append("o.MNU_WIDTH as width,")
		.append("o.MNU_HEIGHT as height,")
		.append("o.MNU_ICON as menuIcon,")
		.append("o.MNU_ICON_CLS as menuIconCls,")
		.append("o.MNU_URL as url,")
		.append("o.MNU_PARENT_ID as parentID,")
		.append("o.MNU_DESC as description,")
		.append("0 as checked,")
		.append("o.MNU_ACTIVE as active,")
		.append("decode(sign(count(sub.ID)),1,0,1) as leaf")
		.append(" from SYS_MENU o")
		.append(" left join")
		.append(" SYS_MENU sub on o.ID = sub.MNU_PARENT_ID")
		.append(" INNER JOIN SYS_MENU_ROLE_REL rel")
		.append(" ON o.ID         = rel.MENU_ID")
		.append(" INNER JOIN SYS_ROLE r")
		.append(" ON r.ID         = rel.ROLE_ID ");
		if(parameters.containsKey("roleIDs")) {
			String[] roleIDs = (String[]) parameters.get("roleIDs");
			if(roleIDs != null && roleIDs.length > 0) {
				buf.append(" AND r.ID IN (:roleIDs)");
			}
		}
		buf.append(" WHERE");
		if (parameters.containsKey("parentID"))
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MENU org WHERE org.MNU_PARENT_ID = :parentID AND org.MNU_ACTIVE = 1)");
		else if(parameters.containsKey("rootID"))
			buf.append(" o.ID = :rootID");
		else
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MENU org WHERE org.MNU_PARENT_ID IS NULL AND org.MNU_ACTIVE = 1)");
		buf.append(" AND o.REMOVED = 0");
		buf.append(
				" group by o.ID,o.MNU_CODE,o.MNU_NAME,o.MNU_TEXT,o.MNU_TAB_INDEX,o.MNU_WIDTH,o.MNU_HEIGHT,o.MNU_ICON,o.MNU_ICON_CLS,o.MNU_URL,o.MNU_PARENT_ID,o.MNU_DESC,o.MNU_ACTIVE");
	
		String sql = buf.toString();
		List<MenuCheckedTree> list = null;
		list = dao
		.executeNativeQuery(sql, parameters, MenuCheckedTree.class,
				"com.maywide.jdp.system.entities.Menu.menuCheckedTree");
		
		buf = new StringBuffer()
		.append("select distinct o.ID as id,")
		.append("o.MNU_CODE as code,")
		.append("o.MNU_NAME as name,")
		.append("o.MNU_TEXT as text,")
		.append("o.MNU_TAB_INDEX as tabIndex,")
		.append("o.MNU_WIDTH as width,")
		.append("o.MNU_HEIGHT as height,")
		.append("o.MNU_ICON as menuIcon,")
		.append("o.MNU_ICON_CLS as menuIconCls,")
		.append("o.MNU_URL as url,")
		.append("o.MNU_PARENT_ID as parentID,")
		.append("o.MNU_DESC as description,")
		.append("1 as checked,")
		.append("o.MNU_ACTIVE as active,")
		.append("decode(sign(count(sub.ID)),1,0,1) as leaf")
		.append(" from SYS_MENU o")
		.append(" left join")
		.append(" SYS_MENU sub on o.ID = sub.MNU_PARENT_ID")
		.append(" INNER JOIN SYS_MENU_ROLE_REL rel")
		.append(" ON o.ID         = rel.MENU_ID")
		.append(" INNER JOIN SYS_ROLE r")
		.append(" ON r.ID         = rel.ROLE_ID ");
		if(parameters.containsKey("roleID"))
			buf.append(" AND r.ID = :roleID");
		buf.append(" WHERE");
		if (parameters.containsKey("parentID"))
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MENU org WHERE org.MNU_PARENT_ID = :parentID AND org.MNU_ACTIVE = 1)");
		else if(parameters.containsKey("rootID"))
			buf.append(" o.ID = :rootID");
		else
			buf.append(" o.ID IN(SELECT org.ID FROM SYS_MENU org WHERE org.MNU_PARENT_ID IS NULL AND org.MNU_ACTIVE = 1)");
		buf.append(" AND o.REMOVED = 0");
		buf.append(
				" group by o.ID,o.MNU_CODE,o.MNU_NAME,o.MNU_TEXT,o.MNU_TAB_INDEX,o.MNU_WIDTH,o.MNU_HEIGHT,o.MNU_ICON,o.MNU_ICON_CLS,o.MNU_URL,o.MNU_PARENT_ID,o.MNU_DESC,o.MNU_ACTIVE");
	
		sql = buf.toString();
		List<MenuCheckedTree> checkedList = null;
		checkedList = dao
				.executeNativeQuery(sql, parameters, MenuCheckedTree.class,
						"com.maywide.jdp.system.entities.Menu.menuCheckedTree");
		if(checkedList != null && !checkedList.isEmpty()) {
			for(MenuCheckedTree checkedMenu : checkedList) {
				if(list.contains(checkedMenu)) {
					list.remove(checkedMenu);
					list.add(checkedMenu);
				}
			}
		}
		
		return list;
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public Page page(int first, int limit, String sort, String dir,
			Map<String, Object> conditions, Map<String, Object> parameters)
			throws Exception {
		Page page = null;

		String queryString = "select o from Menu as o inner join o.roles as r";
		String countQueryString = "select count(o.id) from Menu as o inner join o.roles as r";
		if(conditions == null)
			conditions = new HashMap<String,Object>();
		if(!conditions.containsKey("parentID"))
			conditions.put("noParentID", null);
		PageQueryTemplate template = new PageQueryTemplate(queryString,
				countQueryString, first, limit, sort, dir);
		page = dao.executePageQuery(template, conditions, null);

		return page;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.maywide.jdp.system.permission.bean.IMenuBean#getStartMenus(com.maywide
	 * .jdp.system.vo.Context)
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Menu> getStartMenus(Context context) throws Exception {
		String[] roleIDs = context.getRoleIDs();
		Map conditions = new HashMap<String, Object>();
		conditions.put("roleIDs", roleIDs);

		String name = "com.maywide.jdp.system.entities.Menu.personalMenu";
		return dao.executeNamedQuery(name, conditions, null, Menu.class);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Menu> findMenus(String roleID) throws Exception {
		Map parameters = new HashMap<String, Object>();
		parameters.put("roleID", roleID);
		String name = "com.maywide.jdp.system.entities.Menu.findMenus";
		return dao.executeNamedQuery(name, null, parameters, Menu.class);
	}

}
